package com.wl.springsecuritystudy.controller;

import com.wl.springsecuritystudy.entity.User;
import com.wl.springsecuritystudy.mapper.UserMapper;
import com.wl.springsecuritystudy.thread.support.AfterCommitExecutor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@RestController
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AfterCommitExecutor afterCommitExecutor;

    @GetMapping("/update/user")
    @Transactional(rollbackFor = Exception.class)
    public String updateUser(){
        List<User> users = userMapper.selectList(null);
        User user = users.get(0);
        user.setLastupdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        if(TransactionSynchronizationManager.isSynchronizationActive()){
            System.out.println("有事物");
        }
        afterUpdateUser(user.getUserName());
        return "ok";
    }

    public void afterUpdateUser(String userName){
        afterCommitExecutor.execute(()->{
            System.out.println("更新了 " + userName + "的时间");
        });
    }
}
